import { Component, ElementRef, EventEmitter, Injector, Output, ViewChild } from '@angular/core';
import { AppComponentBase } from '@shared/common/app-component-base';
import { MaterialIntoServiceProxy, WlReleaseStockBillEditDto } from '@shared/service-proxies/service-proxies';
import { ModalDirective } from 'ngx-bootstrap';
import { finalize } from 'rxjs/operators';
import * as moment from 'moment';

@Component({
    selector: 'createOrEditWlModal',
    templateUrl: './create-or-edit-wl-modal.component.html'
})
export class CreateOrEditWlModalComponent extends AppComponentBase {

    @ViewChild('createOrEditModal') modal: ModalDirective;

    @ViewChild('billDatePicker') billDatePicker: ElementRef;
    @ViewChild('scanTimePicker') scanTimePicker: ElementRef;

    @Output() modalSave: EventEmitter<any> = new EventEmitter<any>();

    active = false;
    saving = false;

    wl = new WlReleaseStockBillEditDto();

    constructor(
        injector: Injector,
        private _intoService: MaterialIntoServiceProxy
    ) {
        super(injector);
    }

    show(id?: number): void {
        const self = this;
        self.active = true;

        self._intoService.getReleaseStockBillForEdit(id)
        .subscribe(result => {
            self.wl = result;

            if (this.wl.billDate.get('year') === 1) {
              this.wl.billDate = undefined;
            }

            $(this.billDatePicker.nativeElement).datetimepicker({
              locale: 'zh-CN',
              format: 'L'
            }).on('dp.change', e => {
              this.wl.billDate = moment.utc(e.date);
            });

            $(this.scanTimePicker.nativeElement).datetimepicker({
              locale: 'zh-CN',
              format: 'L'
            }).on('dp.change', e => {
              this.wl.scanTime = moment.utc(e.date);
            });


            self.modal.show();
        });
    }

    save(): void {
        const self = this;

        this.saving = true;
        this._intoService.createOrUpdateReleaseStockBill(this.wl)
            .pipe(finalize(() => this.saving = false))
            .subscribe(() => {
                this.notify.info(this.l('SavedSuccessfully'));
                this.close();
                this.modalSave.emit(null);
            });
    }

    close(): void {
        this.active = false;
        this.modal.hide();
    }
}
